﻿/*
   Copyright 2014 Dmitry Bratus

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

using AopAlliance.Intercept;
using Flower.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Flower.Client
{
    internal class AutorefreshingProxyInterceptor : IMethodInterceptor
    {
        private static readonly Log Log = LogManager.CreateLog(typeof(AutorefreshingProxyInterceptor).Name);

        private readonly IFlowerClient _flowerClient;
        private readonly TimeSpan _expirationInterval;
        private readonly string _servicePath;

        private object _service;
        private DateTime _expiresAt;

        public AutorefreshingProxyInterceptor(IFlowerClient flowerClient, string servicePath, TimeSpan expirationInterval)
        {
            _flowerClient = flowerClient;
            _servicePath = servicePath;
            _expirationInterval = expirationInterval;
            _expiresAt = DateTime.Now;
        }

        public object Invoke(IMethodInvocation invocation)
        {
            var now = DateTime.Now;
            if (now >= _expiresAt)
            {
                Log.Trace(() => string.Format("Service {0} has been expired and needs to be refreshed.", _servicePath));

                _service = _flowerClient.GetService<object>(_servicePath);
                _expiresAt = now + _expirationInterval;
            }

            try
            {
                return invocation.Method.Invoke(_service, invocation.Arguments);
            }
            catch(TargetInvocationException ex)
            {
                throw ex.InnerException;
            }
        }
    }
}
